// pages/createScore/createScore.js
Page({
    data: {
      dailyGrade:0,//每日一评分
      dailyGradeType:["仅限一次","每天一次"],
      descImgUrls:["../../imgs/addDescImg.png"],//描述图片
      imgUrl:'../../imgs/addImg.png',//自定义分享图
      needPersonalInformation:false,//是否需要个人信息
      allowGroupGrade:0,//只允许群成员打分
      formTitle: '',
      formDesc: '',
      nowDate: '',
      nowTime: '',
      endDate: '',
      isAnonymous: false,
      buttonDisable:false,
    },
    onLoad(options) {
      this.formReset()
    },
    onTitleInputChange(e) {
      this.setData({
        formTitle: e.detail.value
      })
    },
    onDescChange(e) {
      this.setData({
        formDesc: e.detail.value
      })
    },
    onTapUploadImg(e) {
      console.log(e)
      let index = e.currentTarget.dataset.optionIndex
      let that = this
      wx.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'],
          success (res) {
            // tempFilePath可以作为img标签的src属性显示图片
            const tempFilePaths = res.tempFilePaths
            wx.uploadFile({
              //url: 'https://www.intohash.com/vote_backend/main/uploadImg', //仅为示例，非真实的接口地址
              url: 'http://localhost:8010/vote_backend/main/uploadImg',
              filePath: tempFilePaths[0],
              name: 'file',
              success (res){
                const data = res.data
                let imgurl = JSON.parse(data).data
                let imgList = that.data.optionImgList
                imgList[index] = imgurl
                that.setData({
                    optionImgList:imgList
                })
                console.log(imgList)
              }
            })
            /*let imgList = that.data.optionImgList
            imgList[index] = tempFilePaths
            that.setData({
              optionImgList:imgList
            })*/
          }
        })
  },
  onTapUploadDescImg(e) {
    console.log(e)
    let that = this
    wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success (res) {
          // tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths
          wx.uploadFile({
            //url: 'https://www.intohash.com/vote_backend/main/uploadImg', //仅为示例，非真实的接口地址
            url: 'http://localhost:8010/vote_backend/main/uploadImg',
            filePath: tempFilePaths[0],
            name: 'file',
            success (res){
              const data = res.data
              let imgurl = JSON.parse(data).data
              let descImgList=[]
              descImgList.push(imgurl)
              that.setData({
                descImgUrls:descImgList
              })
            }
          })
          // let imgList = that.data.descImgUrls
          // imgList = tempFilePaths
          // that.setData({
          //   descImgUrls:imgList
          // })
        }
      })
  },
  onTapUploadShareImg(e) {
    console.log(e)
    //let index = e.currentTarget.dataset.optionIndex
    let that = this
    wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success (res) {
          // tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths
          wx.uploadFile({
            //url: 'https://www.intohash.com/vote_backend/main/uploadImg', //仅为示例，非真实的接口地址
            url: 'http://localhost:8010/vote_backend/main/uploadImg',
            filePath: tempFilePaths[0],
            name: 'file',
            success (res){
              const data = res.data
              let imgurl = JSON.parse(data).data
              that.setData({
                imgUrl:imgurl
              })
              console.log(imgurl)
            }
          })
          /*let imgList = that.data.imgUrl
          imgList = tempFilePaths
          that.setData({
            imgUrl:imgList
          })*/
        }
      })
  },
    onChangedailyGrade(e) {
      this.setData({
        dailyGrade: e.detail.value
      })
    },
    onChangedisplayOption(e) {
      this.setData({
        displayOption: e.detail.value
      })
    },
    onChangeshuffleOptions(e) {
      this.setData({
        shuffleOptions: e.detail.value
      })
    },
    onChangeneedPersonalInformation(e) {
      this.setData({
        needPersonalInformation: e.detail.value
      })
    },
    onChangenowTime(e) {
      const nowTime = e.detail.value;
      const nowDate = this.data.nowDate;
      const endDate = nowDate + ' ' + nowTime;
      this.setData({
        nowTime:nowTime,
        endDate: endDate
      })
    },
    onChangenowDate(e) {
      const nowDate = e.detail.value;
      const nowTime = this.data.nowTime;
      const endDate = nowDate + ' ' + nowTime;
      this.setData({
        nowDate:nowDate,
        endDate: endDate
      })
    },
    onChangeIsAnonymous(e) {
      this.setData({
        isAnonymous: e.detail.value
      })
    },
    onChangeallowGroupGrade(e) {
      this.setData({
        allowGroupGrade: e.detail.value
      })
    },
    // 校验表单数据是否完整，如果校验通过就返回null，否则返回需要提示的文字
    checkFormValid() {
      if (!this.data.formTitle) {
        return '标题不能为空'
      }
      return null
    },
  
  
    // 时间校验函数
    checkExpired(endDate) {
      const now = new Date();
      const endDateArray = endDate[0].split('-') // 将字符串分割成字符数组，分隔符为-
      const endYear = Number(endDateArray[0]) // 取字符数组中的年份，并将数据类型转换为number
      const endMonth = Number(endDateArray[1]) // 取字符数组中的月份，并将数据类型转换为number
      const endDay = Number(endDateArray[2]) // 取字符数组中的日期，并将数据类型转换为number
  
      const endDateArray2 = endDate[1].split(':') 
      const endHour = Number(endDateArray2[0]) 
      const endMinute = Number(endDateArray2[1]) 
  
      const time = new Date(endYear,endMonth-1,endDay,endHour,endMinute);
      console.log('now',now)
      console.log('time',time)
      if(now > time){
        console.log('打分时间已截止');
        return true;
      }else{
        console.log('投票时间未截止');
        return false;
      }
    },
  
   
  
    formSubmit() {
      // 提交前需要先对表单内容进行校验
      const msg = this.checkFormValid()
      if (msg) {        // 在if判断时，null会被转换为false
        wx.showToast({  // 调用提示框API显示提示内容
          title: msg,   // 提示框中的文字内容
          icon: 'none'  // 提示框的图标，none表示没有图标
        })
        return           // 提前返回，函数会在这里结束，后面的内容不会执行
      }
  
      let endDateAndTimeArray = this.data.endDate.split(' ');
      let that = this
      wx.showModal({
        title: '温馨提示',
        content: '打分创建后不支持再次修改，请确认',
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            if(that.checkExpired(endDateAndTimeArray) == false){ // 选项数限制正确，投票时间未截止
              wx.showLoading({
                title: '加载中',
                mask:true
              })
              that.setData({
                buttonDisable:!that.data.buttonDisable
              })
              // 校验通过时后面的内容才会被执行
              const formData = {  // 将表单的数据放到一个formData对象中
                "endDate": that.data.endDate,
                "isAnonymous": that.data.isAnonymous?1:0,
                "dailyGrade": that.data.dailyGrade,
                "needPersonalInformation": that.data.needPersonalInformation?1:0,
                "title": that.data.formTitle,
                "descImgUrls": that.data.descImgUrls,
                "imgUrl": that.data.imgUrl,
                "userId": wx.getStorageSync('userid'),
                "gradeDesc": that.data.formDesc,  
                "onlyGroupMember": that.data.allowGroupGrade?1:0,
              }
              console.log(formData)
              wx.request({
                //url: "https://www.intohash.com/vote_backend/user/addGrade",
                url: "http://localhost:8010/vote_backend/user/addGrade",
                method:"POST",
                data:{
                    "endDate": that.data.endDate,
                    "isAnonymous": that.data.isAnonymous?1:0,
                    "dailyGrade": that.data.dailyGrade,
                    "needPersonalInformation": that.data.needPersonalInformation?1:0,
                    "title": that.data.formTitle,
                    "descImgUrls": that.data.descImgUrls,
                    "imgUrl": that.data.imgUrl,
                    "userId": wx.getStorageSync('userid'),
                    "gradeDesc": that.data.formDesc,  
                    "onlyGroupMember": that.data.allowGroupGrade?1:0,
                },
                success: function (e) {
                  //返回userid 用户评论
                    wx.hideLoading()
                  console.log('创建投票成功')
                  console.log(e)
                  let gradeid = e.data.data.gradeId
                  
                  wx.redirectTo({       // 自动跳转到参与投票页面
                    url: '/pages/score/score?gradeID=' + gradeid + '&CreatedOrJoined=0',//0代表从我创建的页面进入
                  })
                }
                , fail: function (e) {
                  wx.hideLoading()
                  that.setData({
                    buttonDisable:!that.data.buttonDisable
                  })
                  wx.showToast({            // 创建打分失败时，显示提示框提示用户
                    title: '创建打分失败',  // 提示框中的文字内容
                    icon: 'none'            // 提示框的图标，none表示没有图标
                  })
                }
              });
  
            }
            else{
              wx.showModal({ // 选项数限制正确，打分时间已截止
                title:'提示',
                content: '请设置正确的打分截止日期',
                confirmText:'我知道了',
                showCancel:false
              })
  
            }
        
          } else if (res.cancel) {
            console.log('用户点击取消') 
          }
        }
      })
    },
    formReset() {
      const now = new Date()
      const nowYear = now.getFullYear()
      const nowMonth = now.getMonth()+1
      const nowDay = now.getDate()
      const nowHour = now.getHours();
      const nowMinute = now.getMinutes();
      const nowDate = nowYear +
        '-' +
        ((nowMonth < 10) ? ('0' + nowMonth) : nowMonth) +
        '-' +
        ((nowDay < 10) ? ('0' + nowDay) : nowDay);
  
      const nowTime = ((nowHour < 10)?('0' + nowHour) : nowHour) +
        ':' +
        ((nowMinute < 10)?('0' + nowMinute) : nowMinute) ;
      this.setData({
        nowDate,
        nowTime,
        endDate: nowDate+ ' ' + nowTime,
        formTitle: '',
        formDesc: '',
        isAnonymous: false,
        dailyGrade: 0,
        needPersonalInformation: false,
        allowGroupGrade:0
      })
    }
  })
  